<?php

namespace Service\WebSocketService\WebSocketRouter;

use Service\BaseService;
use App\Model\CommodityModel\CommodityArchives;
use Hyperf\DbConnection\Db;
use Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\WarehouseInfo;

/**
 * top 销售报表导出
 */
class TopSaleReportSocketService extends BaseService {
    public $server;

    public $fd;

    public $default_data = [
        '供应商*',
        '商品名称*',
        '商家SKU编码*',
        '保价天数',
    ];

    public $validate_data = [
        0 => 'require',
        1 => 'require',
        2 => 'require',
        3 => 'require',
    ];

    /**
     * top销售表导出
     * @param object $server
     * @param int $fd
     * @param array $data
     * @param array $sysInfo
     * @param array $excel_hedaer
     * @param array $excel_data
     * @return mixed|array
     */
    public function Export($server, int $fd, array $data, array $sysInfo, array $excel_hedaer, array $excel_data) {
        $this->server = $server;
        $this->fd               = $fd;
        $params                 = $data;
        if (empty($params['store_id'])) {
            $send    = Normal::returnWsStatus(Normal::WS_ERROR, "仓库id不能为空", [
                'download_url' => null,
                'msg'          => "仓库id不能为空",
                'percent'      => 100,
            ]);
            $sendMsg = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->server->push($this->fd, $sendMsg);
            return $send;
        }
        $search = $this->getSearchParam(['requestData' => $params]);
        $where  = $search['where'];
        $limit  = $search['limit'];
        //通过仓库id查询出仓库和供应商信息
        $warehouse = Warehouseinfo::instance()
            ->alias('w')
            ->field(implode(",", [
                "w.WarehouseName as warehouse_name",
                "w.id as store_id",
                "sc.SupplierName as supplier_name",
            ]))
            ->join('suppliercompany_s2b sc', 'sc.id = w.SupplierID')
            ->where("w.id", $params['store_id'])
            ->find()
            ->toArray();
        if (empty($warehouse)) {
            $send    = Normal::returnWsStatus(Normal::WS_ERROR, "该仓库不存在", [
                'download_url' => null,
                'msg'          => "该仓库不存在",
                'percent'      => 100,
            ]);
            $sendMsg = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->server->push($this->fd, $sendMsg);
            return $send;
        }

        $importData = [];
        $model      = OrderSupplierGoods::instance();
        $orderModel = $model
            ->alias('osg')
            ->field(implode(",", [
                "sum(osg.total) as sum",
                "goods_name",
            ]))
            ->join('commodity.commodityarchives_s2b ca', 'osg.goods_id = ca.id')
            ->where($where)
            ->group("osg.skucode")
            ->select();
        if ($orderModel) {
            $orderList = $orderModel->toArray();
            $tmpData   = [];
            foreach ($orderList as $order) {
                $tmpData[] = $this->getRowData($order, $warehouse, $search);
            }
            $importData = array_merge($importData, $tmpData);
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->server->push($this->fd, $send);

        $fileName     = "top销售表明细导出";
        $headArr      = $this->getColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url
        ]);
    }

    public static function getSearchParam($parameters) {
        $search = $parameters['requestData'];
        $limit  = isset($search['limit']) ? $search['limit'] : 100;
        $where  = "osg.store_id=" . (string)$search['store_id'];
        //开始时间
        $start_time = strtotime(date("Y-m-d", time()) . " 00:00:00");
        $startTime  = date("Y-m-d", time());
        //结束时间
        $end_time = time();
        $endTime  = date("Y-m-d", time());

        if (!empty($search['start_time'])) {
            $start_time = strtotime($search['start_time']);
            $startTime  = $search['start_time'];
        }
        if (!empty($search['end_time'])) {
            $end_time = strtotime($search['end_time']);
            $endTime  = $search['end_time'];
        }
        if (!empty($search['second_class_id'])) {
            $where .= " and ca.SecondClassificationID=" . $search['second_class_id'];
        }

        $where .= " and osg.cd >= {$start_time} and osg.cd <= {$end_time}";
        return [
            'limit'      => $limit,
            'where'      => $where,
            'start_time' => $startTime,
            'end_time'   => $endTime,
        ];
    }

    public function getRowData($goodsInfo, $warehouse, $search) {
        return [
            $search['start_time'] . "~" . $search['end_time'],
            $warehouse['warehouse_name'],
            $warehouse['supplier_name'],
            $goodsInfo['goods_name'],
            $goodsInfo['sum'],
        ];
    }

    public function getColumns() {
        return [
            '时间段',
            '仓库',
            '供应商',
            '商品名称',
            '商品销售额',
        ];
    }

    /**
     * 验证器
     * @param $data
     * 0 = 供应商   1 = 商品名称  2 = 商家sku 3 = 报价天数
     */
    public function validate($data) {
        foreach ($this->validate_data as $k => $i) {
            if (empty($data[$k])) {
                return Normal::returnCode(Normal::FAIL, $this->default_data[$k] . '不能为空', []);
            }
        }
        return Normal::returnCode(Normal::SUC, '验证成功', []);

    }
}